<?php
class PNItem extends PNObject {
  function PNItem($init=null, $where='')
  {
    $this->PNObject();

    $this->_objType       = 'ishopstore_item';
    $this->_objField      = 'id';
    $this->_objPath       = 'form';
    $this->_init($init, $where);
  }

  function insertPostProcess(){
    Loader::loadClass('DataUtilEx', "modules/IShopStore/pnincludes");
    $id = DBUtil::getInsertID ($this->_objType, $this->_objField);

    if ($id){
      ///////////set ref_id/////////
      //////get category prefix/////

      $cat_id = $this->_objData['categories_id'];
      $cat_prefix = DBUtil::selectFieldByID('ishopstore_categories', 'prefix', $cat_id);
      $user = DataUtilEx::fillString($this->_objData['cr_uid'],2,'0');
      $item_ref_id = DataUtilEx::fillString($id,4,'0', $cat_prefix . '_');
      //echo $item_ref_id; exit;
      $object = array('id'=>$id,
                      'item_ref_id'=>$item_ref_id);
      DBUtil::updateObject($object,$this->_objType);
      $this->uploadFiles($id);
      $this->checkHasFile($id);
    }
  }

  function updatePostProcess(){
    //set thumb to image status
    $form = FormUtil::getPassedValue ('form', false );
    $id = $this->_objData['id'];
    $item_ref_id = DBUtil::selectFieldByID('ishopstore_item', 'item_ref_id', $id);

    //set image thumb
    $firstimage_id = $form['firstimage'];
    if ($firstimage_id && $id){
      //clear status
      $object = array('status' => 0);
      $where = "WHERE img_item_ref_id = '$item_ref_id'";
      DBUtil::updateObject($object,'ishopstore_images',$where);
      //set thumb
      $object = array('id' => $firstimage_id , 'status' => 1);
      DBUtil::updateObject($object,'ishopstore_images');

      //Set first image to inventory table
      $columnArray = array('imagename','thumbname');
      $firstimage = DBUtil::selectObject('ishopstore_images' ,
                                         "WHERE img_item_ref_id = '$item_ref_id' AND img_status = 1",
                                         $columnArray
                                         );
      $object = array('firstfilename'=>$firstimage['imagename'] , 
                      'firstthumbname'=>$firstimage['thumbname']);
      $where  = " itm_id = ".$id;
      DBUtil::updateObject($object,'ishopstore_item',$where);
    }

    //delete image
    foreach($form['file_delete'] as $delete_id){
      //Delete file from directory
      $columnArray = array('imagename','thumbname');
      $objectImageName = DBUtil::selectObject('ishopstore_images',"img_id = '$delete_id)'", $columnArray);
            unlink($objectImageName['imagename']);
            unlink($objectImageName['thumbname']);

      DBUtil::deleteObjectByID('ishopstore_images',$delete_id);
    }
    $this->uploadFiles($id);
    $this->checkHasFile($id);
  }


  function deletePreProcess(){
    //echo "deletePreProcess"; exit;

    $id = $this->_objData['id'];
    $item_ref_id = DBUtil::selectFieldByID('ishopstore_item', 'item_ref_id', $id);
    if ($id){

      //Delete file from directory
      $objects = array('imagename','thumbname','path');
      $objectImagename = DBUtil::selectObjectArray('ishopstore_images',"WHERE img_item_ref_id = '$item_ref_id' "
                                                        , '',-1, -1,'', null, null, $objects);
      $path = $objectImagename[0]['path'];
      foreach($objectImagename as $data){
        unlink($data['imagename']);
        unlink($data['thumbname']);
        //unlink('resource/ishopstore_upload/images/Item/'.$data['thumbname']);
      }
//echo "deletePreProcess";  exit;
      //delete image
      DBUtil::deleteWhere('ishopstore_images',"WHERE img_item_ref_id = '$item_ref_id' ");
      //delete item
      DBUtil::deleteWhere('ishopstore_item',"WHERE itm_id = '$id'");
      $this->removeDirRecurse($path);
    }

  }

  
  function selectExtendResult(){
    $id = FormUtil::getPassedValue ('id', false );
    $item_ref_id = DBUtil::selectFieldByID('ishopstore_item', 'item_ref_id', $id);
    $result = array();
    $objects = array('id', 'item_ref_id', 'path', 'imagename', 'thumbname');
    if ($id){
      $result['files'] = DBUtil::selectObjectArray('ishopstore_images' , "WHERE img_item_ref_id = '$item_ref_id' " ,
                                                     'img_id',-1, -1,'', null, null, $objects);
    }
/*
    $objectsSubCategories = array('id', 'name');
    $result['subcategories'] = DBUtil::selectObjectArray('IShopStore_subcategories' , " " ,
                                                     '',-1, -1,'', null, null, $objectsSubCategories);
*/

    return $result;
  }

  function uploadFiles($id){
    $item_ref_id = DBUtil::selectFieldByID('ishopstore_item', 'item_ref_id', $id);
    $count = DBUtil::selectObjectCount('ishopstore_images' , "WHERE img_item_ref_id = '$item_ref_id' ");
    if ($id && in_array(0,$_FILES['images']['error'])){
      $images = $_FILES['images'];
      //var_dump($images); exit;
      //Step 1: Make [resource] directory
      if (!is_dir("resource/")) {
        mkdir("resource/", 0777);
      }
    
      //Step 2: Make [ishopstore_upload] directory
      if (!is_dir("resource/ishopstore_upload/")) {
        mkdir("resource/ishopstore_upload/", 0777);
      }
      copy('modules/IShopStore/.htaccess', "resource/ishopstore_upload/.htaccess");
      copy('modules/IShopStore/index.html', "resource/ishopstore_upload/.html");
  
      //Step 3: Make [images] directory
      if (!is_dir("resource/ishopstore_upload/images/")) {
        mkdir("resource/ishopstore_upload/images/", 0777);
      }
      copy('modules/IShopStore/.htaccess','resource/ishopstore_upload/images/.htaccess');
      copy('modules/IShopStore/index.html','resource/ishopstore_upload/images/.html');
      
      //Generate user folder    
      $user = InnoUtil::getUserInfo();     
      $userFolder = InnoUtil::encrypt($user['uname'], "phuketinnova");
      
      $user_imagepath = "resource/ishopstore_upload/images/".$userFolder;
      $user_thumbspath = "resource/ishopstore_upload/images/".$userFolder;
             
      if(!is_dir($user_imagepath)){
        mkdir($user_imagepath, 0755);
        copy(HTACCESS_PATH, $user_imagepath."/.htaccess");
        copy(HTML_BLANK_PATH, $user_imagepath."/index.html");          
      }  
       
      if(!is_dir($user_thumbspath)){
        mkdir($user_thumbspath, 0755);
        copy('modules/IShopStore/.htaccess', $user_thumbspath."/.htaccess");
        copy('modules/IShopStore/index.html', $user_thumbspath."/index.html");          
      }            
          
          
      $imagespath = "resource/ishopstore_upload/images/".$userFolder."/".$id."/";
      $thumbspath = "resource/ishopstore_upload/images/".$userFolder."/".$id."/thumb/";

      //Make topic image directory by id
      if (!is_dir($imagespath)) {
        mkdir($imagespath, 0755);
       }
       copy('modules/IShopStore/.htaccess',$imagespath);
       copy('modules/IShopStore/index.html',$imagespath);
      
      //Make topic thumb directory by id
      if (!is_dir($thumbspath)) {
        mkdir($thumbspath, 0755);
       }
       copy('modules/IShopStore/.htaccess',$thumbspath);
       copy('modules/IShopStore/index.html',$thumbspath);
      

      foreach ($images["error"] as $key => $error){
        if ($error == 0){
            //Gennerate next id
            $image_id = DBUtil::selectFieldMax( 'ishopstore_images', 'id', 'MAX', '');
            if($image_id == null){
              $next_id = 1;
            }else{
              $next_id = $image_id+1;
            }

            $tmp_name = $images["tmp_name"][$key];
            $fliename = $images["name"][$key];

////////////////////////// get the extension of the file in a lower case format/////////////////////////////////////
            $filename = stripslashes($fliename);
            $i = strrpos($filename,".");
            if (!$i) { return ""; }
            $l = strlen($filename) - $i;
            $ext = substr($filename,$i+1,$l);
            $extension = strtolower($ext);

////////////////////////////generate new file&path//////////////////////////////////////////////////////////////////
            $rootname       = $next_id.time().".".$extension;
            $filename_temp  = "images_".$id.$rootname;
            $thumbname_temp = "thumbs_".$id.$rootname;
            $imgpath        = $imagespath.$filename_temp;
            $tmbpath        = $thumbspath.$thumbname_temp;

/////////////////////////Copy images to directory///////////////////////////////////////////////////////////////////
            copy($tmp_name,$imgpath);

            if(strcmp("jpg",$extension)==0)
              $src_img=imagecreatefromjpeg($tmp_name);

            if(strcmp("jpeg",$extension)==0)
              $src_img=imagecreatefromjpeg($tmp_name);

            if(strcmp("png",$extension)==0)
              $src_img=imagecreatefrompng($tmp_name);

            if(strcmp("gif",$extension)==0)
              $src_img=imagecreatefromgif($tmp_name);

            if(strcmp("bmp",$extension)==0)
              $src_img=imagecreatefromwbmp($tmp_name);

            //gets the dimmensions of the image
            $old_x=imageSX($src_img);
            $old_y=imageSY($src_img);

            // next we will calculate the new dimmensions for the thumbnail image
            // the next steps will be taken:
            // 1. calculate the ratio by dividing the old dimmensions with the new ones
            // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
            // and the height will be calculated so the image ratio will not change
            // 3. otherwise we will use the height ratio for the image
            // as a result, only one of the dimmensions will be from the fixed ones
            $new_w = 200;
            $new_h = 150;
            $ratio1=$old_x/$new_w;
            $ratio2=$old_y/$new_h;
            if($ratio1>$ratio2) {
              $thumb_w=$new_w;
              $thumb_h=$old_y/$ratio1;
            }else{
              $thumb_h=$new_h;
              $thumb_w=$old_x/$ratio2;
            }

            // we create a new image with the new dimmensions
            $dst_img   = ImageCreateTrueColor($thumb_w,$thumb_h);

            // resize the big image to the new created one
            $thumb = imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

            $thumbsize = '1000';
            $thumbtype = $filetype;

            // output the created image to the file. Now we will have the thumbnail into the file named by $filename
            if(strcmp("png",$extension)==0){
              imagepng($dst_img,$tmbpath);
            }else if(strcmp("jpg",$extension)==0){
              imagejpeg($dst_img,$tmbpath);
            }else if(strcmp("jpeg",$extension)==0){
              imagejpeg($dst_img,$tmbpath);
            }else if(strcmp("gif",$extension)==0){
              imagegif($dst_img,$tmbpath);
            }else if(strcmp("bmp",$extension)==0){
              imagewbmp($dst_img,$tmbpath);
            }else {
              imagejpeg($dst_img,$tmbpath);
            }

            //destroys source and destination images.
            imagedestroy($dst_img);
            imagedestroy($src_img);

            $objects = array(
                            'id'            => $next_id,
                            'path'          => $imagespath,
                            'item_ref_id'   => $item_ref_id,
                            'imagename'     => $imgpath,
                            'thumbname'     => $tmbpath, 
                            'status'        => 1
                           );

          DBUtil::insertObject($objects,'ishopstore_images');

        }
        
      }
      //Set default images
      //if ($id && $count==0){
      if ($id){
        $object = array('firstfilename'=>$imagespath.$filename_temp , 'firstthumbname'=>$thumbspath.$thumbname_temp);
        $where  = "itm_item_ref_id = '$item_ref_id'";
        DBUtil::updateObject($object,'ishopstore_item',$where);
      }
    }
    $this->checkHasFile($id);
  }
//img_item_ref_id = '$item_ref_id'
  function checkHasFile($id){
    $item_ref_id = DBUtil::selectFieldByID('ishopstore_item', 'item_ref_id', $id);
    $count = DBUtil::selectObjectCount( 'ishopstore_images', "img_item_ref_id = '$item_ref_id' ", 'id', true, null);
    if ($count != 0 && $id){
      $object = array('has_file' => $count);
      DBUtil::updateObject( $object, 'ishopstore_item', " itm_item_ref_id = '$item_ref_id' ");
    }
    else{
      $object = array('has_file' => 'NULL');
      DBUtil::updateObject( $object, 'ishopstore_item', " itm_item_ref_id = '$item_ref_id' ");
    }
  }

  function removeDirRecurse($path)
  {
      $path= rtrim($path, '/').'/';
      $handle = opendir($path);
      for (;false !== ($file = readdir($handle));)
          if($file != "." and $file != ".." )
          {
              $fullpath= $path.$file;
              if( is_dir($fullpath) )
              {
                  $this->removeFile($fullpath);
                  rmdir($fullpath);
              }
              else
                unlink($fullpath);
          }
      closedir($handle);
  }

  function removeFile($file)
  {
    if (is_file($file)){
      @unlink($file);
    }
  }


}